<!-- 

if (formType.value == 'create') {
      totalItemsPrice.value.totalNoTax = 0
      totalItemsPrice.value.totalWithTax = 0
      const { insertRecords } = $table.getRecordset()
      // console.log(insertRecords, $table.getRecordset(), $table.getTableData())
      insertRecords.forEach((item) => {
        totalItemsPrice.value.totalNoTax += parseFloat(item.totalWithoutTax)
        totalItemsPrice.value.totalWithTax += parseFloat(item.totalWithTax)
      })
      footerMethodData.value[1].columns![0].content![0].price = totalItemsPrice.value.totalNoTax
      footerMethodData.value[1].columns![0].content![1].price = totalItemsPrice.value.totalNoTax
      footerMethodData.value[1].columns![1].content![0].price = totalItemsPrice.value.totalWithTax
      footerMethodData.value[1].columns![1].content![1].price = totalItemsPrice.value.totalWithTax
    } else {
      const { tableData } = $table.getTableData()
      tableData.forEach((item) => {
        totalItemsPrice.value.totalNoTax += parseFloat(item.totalWithoutTax)
        totalItemsPrice.value.totalWithTax += parseFloat(item.totalWithTax)
      })
      footerMethodData.value[1].columns![0].content![0].price = totalItemsPrice.value.totalNoTax
      footerMethodData.value[1].columns![0].content![1].price = totalItemsPrice.value.totalNoTax
      footerMethodData.value[1].columns![1].content![0].price = totalItemsPrice.value.totalWithTax
      footerMethodData.value[1].columns![1].content![1].price = totalItemsPrice.value.totalWithTax
    }


 -->
<template>
  <div class="wrap">
    <el-tabs v-model="activeTab" class="demo-tabs w-full" @tab-click="">
      <el-tab-pane label="报价单信息" name="info" class="w-full">
        <div class="cards w-full">
          <div class="baseInfo">
            <el-card>
              <template #header>
                <div class="card-header">
                  <span>基础信息</span>
                </div>
              </template>
              <el-form :inline="true" :model="formInline" class="">
                <el-form-item label="项目信息">
                  <el-input v-model="formInline.projectName" :placeholder="hintText" clearable />
                </el-form-item>
                <el-form-item label="报价单编号">
                  <el-input v-model="formInline.quotationNo" :disabled="true" :placeholder="hintText" clearable />
                </el-form-item>
              </el-form>
            </el-card>
          </div>
          <div class="customerInfo">
            <el-card>
              <template #header>
                <div class="card-header">
                  <span>客户信息</span>
                </div>
              </template>
              <el-form :inline="true" :model="formInline" class="">
                <el-form-item label="客户名称" class="w-80">
                  <el-input v-model="formInline.customerName" :placeholder="hintText" clearable />
                </el-form-item>
                <el-form-item label="客户地址" class="w-100">
                  <el-input v-model="formInline.customerAddress" :disable=true :placeholder="hintText" clearable />
                </el-form-item>
                <el-form-item label="联系人">
                  <el-input v-model="formInline.contactPerson" :placeholder="hintText" clearable />
                </el-form-item>
                <el-form-item label="联系电话">
                  <el-input v-model="formInline.customerTel" :disable=true :placeholder="hintText" clearable />
                </el-form-item>
                <el-form-item label="Email">
                  <el-input v-model="formInline.customerEmail" :placeholder="hintText" clearable />
                </el-form-item>
              </el-form>
            </el-card>
          </div>
          <div class="selfInfo">
            <el-card>
              <template #header>
                <div class="card-header">
                  <span>我方信息</span>
                </div>
              </template>
              <el-form :inline="true" :model="formInline" class="">
                <el-form-item label="我方名称" class="w-80">
                  <el-input v-model="formInline.selfName" :placeholder="hintText" clearable />
                </el-form-item>
                <el-form-item label="我方地址" class="w-100">
                  <el-input v-model="formInline.selfAddress" :placeholder="hintText" clearable />
                </el-form-item>
                <el-form-item label="联系人">
                  <el-input v-model="formInline.selfContactPerson" :disabled="true" :placeholder="hintText" clearable />
                </el-form-item>
                <el-form-item label="联系电话">
                  <el-input v-model="formInline.selfTel" :disabled="true" :placeholder="hintText" clearable />
                </el-form-item>
                <el-form-item label="Email">
                  <el-input v-model="formInline.selfEmail" :disabled="true" :placeholder="hintText" clearable />
                </el-form-item>
              </el-form>
            </el-card>
          </div>
          <div class="quotationInfo">
            <el-card>
              <template #header>
                <div class=" card-header">
                  <span>报价详情</span>
                </div>
              </template>
              <div>
                <vxe-toolbar>
                  <template #buttons>
                  </template>
                </vxe-toolbar>
                <vxe-table height="350" align="center" header-align="center" footer-align="left"
                  :edit-config="{ trigger: 'click', mode: 'row' }" footer-cell-class-name="footerCell"
                  :footer-span-method="footerColspanMethod" :footer-method="footerMethod" :show-footer="true"
                  show-overflow ref="tableRef" max-height="400" :data="tableData">
                  <!-- :edit-config="{ trigger: 'click', mode: 'row' }" @edit-activated="editActivatedEvent" :column-config="{ resizable: true }" -->
                  <vxe-column field="seq" type="seq" width="70" class="h-full">
                    <template #footer="{ row }">
                      <span v-if="row.index == 0" class="!text-xl ml-5" @click="insertEvent()">
                        <svg xmlns="http://www.w3.org/2000/svg" width="1em" height="1em" viewBox="0 0 32 32">
                          <path fill="#409eff"
                            d="M16 2A14.173 14.173 0 0 0 2 16a14.173 14.173 0 0 0 14 14a14.173 14.173 0 0 0 14-14A14.173 14.173 0 0 0 16 2m8 15h-7v7h-2v-7H8v-2h7V8h2v7h7Z" />
                          <path fill="none" d="M24 17h-7v7h-2v-7H8v-2h7V8h2v7h7z" />
                        </svg>
                      </span>
                      <!-- footer child item 2 -->
                      <div class="mid h-full" v-if="row.index == 1">
                        <el-collapse v-model="row_activeNames" class="h-full">
                          <el-collapse-item v-for="(rc, k) in row.columns" :key="k" title="" :name="k + 1">
                            <div class=" w-full">
                              <div class=" inline-flex w-full">
                                <div class="text mr-auto w-[220px] flex items-center">
                                  <span class="!text-xl mr-2 " @click="() => addFinalTaxQuotation(row)"
                                    v-if="rc.icon?.add">
                                    <svg xmlns="http://www.w3.org/2000/svg" width="1em" height="1em"
                                      viewBox="0 0 32 32">
                                      <path fill="#409eff"
                                        d="M16 2A14.173 14.173 0 0 0 2 16a14.173 14.173 0 0 0 14 14a14.173 14.173 0 0 0 14-14A14.173 14.173 0 0 0 16 2m8 15h-7v7h-2v-7H8v-2h7V8h2v7h7Z" />
                                      <path fill="none" d="M24 17h-7v7h-2v-7H8v-2h7V8h2v7h7z" />
                                    </svg>
                                  </span>
                                  {{ rc.text }}
                                </div>
                                <div v-for="(rowColumn, s) in rc.content" :key="s" class="flex-1 text-center"
                                  :class="s < (row.columns.length - 1) ? '' : 'none'">
                                  <span v-if="s == 0 && k > 1">
                                    <el-input size="small" class="!w-28" v-model="quotationDetail.finalQuotation"
                                      :placeholder="hintText" clearable />
                                  </span>
                                  <span class="" v-else>
                                    <span v-if="!rowColumn.prefix">￥{{ !rowColumn.prefix ?
                                      rowColumn.price :
                                      `${rowColumn.prefix} : ${digitUppercase(rowColumn.price)}` }}</span>
                                    <span class=" font-800" v-if="rowColumn.prefix">{{
                                      !rowColumn.prefix ? rowColumn.price :
                                        `${rowColumn.prefix} : ${digitUppercase(rowColumn.price)}` }}</span>
                                  </span>
                                </div>
                                <span @click="(e) => deleteFinalTaxQuotation(e, row)"
                                  class="!text-xl mr-2 absolute right-18 cursor-pointer" v-if="rc.icon?.delete">
                                  <svg t="1726043917540" class="icon" viewBox="0 0 1024 1024" version="1.1"
                                    xmlns="http://www.w3.org/2000/svg" p-id="1013" width="1em" height="1em">
                                    <path d="M512 512m-512 0a512 512 0 1 0 1024 0 512 512 0 1 0-1024 0Z" fill="#d81e06"
                                      p-id="1014"></path>
                                    <path
                                      d="M768 448.512H256c-34.816 0-63.488 28.672-63.488 63.488s28.672 63.488 63.488 63.488h512c34.816 0 63.488-28.672 63.488-63.488s-28.672-63.488-63.488-63.488z"
                                      fill="#ffffff" p-id="1015"></path>
                                  </svg>
                                </span>
                              </div>
                            </div>
                          </el-collapse-item>
                        </el-collapse>
                      </div>
                      <!-- <Icon icon="ep:document-add" /> -->

                    </template>
                  </vxe-column>

                  <vxe-column field="type" title="类别" :edit-render="sexEditRender">
                  </vxe-column>
                  <!-- 下拉 <vxe-column field="type" title="类别" :edit-render="sexEditRender">
                  这之间不能有注释之类的，否则被认为是空的插槽  导致不显示数据
                  </vxe-column>  -->
                  <!-- <template #default="{ row }">
                      <vxe-select class="fixZIndex" size="mini" v-model="quotationDetail.name"
                        :options="opts1"></vxe-select>
                    </template> -->
                  <vxe-column field="name" title="名称" :edit-render="sexEditRender">

                  </vxe-column>
                  <vxe-column field="suggestedPrice" title="建议售价" :edit-render="{ enabled: false }">
                    <template #default="{ row }">
                      <span>{{ row.suggestedPrice }}</span>
                    </template>
                  </vxe-column>
                  <vxe-column field="salePrice" title="未税单价" :edit-render="{ enabled: false }">
                    <template #default="{ row }">
                      <vxe-input size="mini" v-model="quotationDetail.salePrice"></vxe-input>
                    </template>
                  </vxe-column>
                  <vxe-column field="count" title="数量" :edit-render="{ enabled: false }">
                    <template #default="{ row }">
                      <vxe-input size="mini" v-model="quotationDetail.count"></vxe-input>
                    </template>
                  </vxe-column>
                  <vxe-column field="totalWithoutTax" title="未税总价(元)" :edit-render="{ enabled: false }">
                    <template #footer="{ row }">
                      <span>{{ row.totalWithoutTax }}</span>
                    </template>
                  </vxe-column>
                  <vxe-column field="taxRate" title="税率" :edit-render="{ enabled: false }">
                    <template #default="{ row }">
                      <vxe-input size="mini" v-model="quotationDetail.taxRate"></vxe-input>
                    </template>
                  </vxe-column>
                  <vxe-column field="totalWithTax" title="含税总价" :edit-render="{ enabled: false }">
                    <template #footer="{ row }">
                      <span>{{ row.totalWithTax }}</span>
                    </template>
                  </vxe-column>
                  <vxe-column field="memo" title="备注" :edit-render="{ enabled: false }">
                    <template #default="{ row }">
                      <vxe-input size="mini" v-model="quotationDetail.memo"></vxe-input>
                    </template>
                  </vxe-column>
                  <vxe-column title="操作" :edit-render="{ enabled: false }">
                    <template #default="{ row }">
                      <span @click="() => deleteRow(row)" class="!text-xl cursor-pointer">
                        <svg t="1726043917540" class="icon" viewBox="0 0 1024 1024" version="1.1"
                          xmlns="http://www.w3.org/2000/svg" p-id="1013" width="1em" height="1em">
                          <path d="M512 512m-512 0a512 512 0 1 0 1024 0 512 512 0 1 0-1024 0Z" fill="#d81e06"
                            p-id="1014"></path>
                          <path
                            d="M768 448.512H256c-34.816 0-63.488 28.672-63.488 63.488s28.672 63.488 63.488 63.488h512c34.816 0 63.488-28.672 63.488-63.488s-28.672-63.488-63.488-63.488z"
                            fill="#ffffff" p-id="1015"></path>
                        </svg>
                      </span>
                    </template>
                  </vxe-column>
                </vxe-table>
              </div>
            </el-card>

          </div>
          <div class="memo">
            <el-card style="">
              <template #header>
                <div class="card-header">
                  <span>备注信息</span>
                </div>
              </template>
              <el-collapse v-model="activeNames" @change="">
                <el-collapse-item title="" name="1">
                  <div class=" w-full">
                    <div class=" inline-flex"><span>1、交货期：合同签订后：</span> <el-input size="small" class="!w-20"
                        v-model="memo.deadLine" :placeholder="hintText" clearable />
                    </div>
                  </div>
                </el-collapse-item>
                <el-collapse-item title="" name="2">
                  <div class="w-full">
                    <span>2、付款方式：合同签订后：
                      <el-input size="small" class="!w-20 mx-1" v-model="memo.payment.deadLine" :placeholder="hintText"
                        clearable />
                      内预付款支付
                      <el-input size="small" class="!w-20 mx-1" v-model="memo.payment.prePay" :placeholder="hintText"
                        clearable />
                      、到货款支付
                      <el-input size="small" class="!w-20 mx-1 " v-model="memo.payment.afterPay" :placeholder="hintText"
                        clearable />
                      、终验支付
                      <el-input size="small" class="!w-20 mx-1" v-model="memo.payment.endPay" :placeholder="hintText"
                        clearable />
                    </span>
                  </div>
                </el-collapse-item>
                <el-collapse-item title="" name="3">
                  <div class="w-full">
                    <span>3、运输方式</span>
                    <el-select size="small" class="!w-40 ml-5" v-model="memo.delivery" :placeholder="hintText">
                      <el-option v-for="item in [1, 2, 3]" :key="item" :label="item" :value="item" />

                    </el-select>

                  </div>
                </el-collapse-item>
                <el-collapse-item title="" name="4">
                  <div class="w-full">
                    <span>4、质量保证：销售即日起，非人为造成的损坏或故障，质量保证期为 <el-input size="small" class="!w-20 mx-1"
                        v-model="memo.qualityGuarantee" :placeholder="hintText" clearable />
                      年</span>

                  </div>
                </el-collapse-item>
                <el-collapse-item title="" name="4">
                  <div class="w-full">
                    <span>5、报价有效期：签字盖章后，<el-input size="small" class="!w-20 mr-3" v-model="memo.quotationValidity"
                        :placeholder="hintText" clearable />天内有效</span>
                  </div>
                </el-collapse-item>
              </el-collapse>
            </el-card>

          </div>
        </div>
      </el-tab-pane>
      <el-tab-pane label="签核流程" name="flow">
        <div class="signFlow">
          <el-card>
            <template #header>
              <div class="card-header">
                <span class="font-[15px] font-700">签核流程</span>
              </div>
            </template>
            <el-table :data="flowData" stripe style="width: 100%">
              <el-table-column header-align="center" align="center" type="index" label="序号" width="180" />
              <el-table-column header-align="center" align="center" prop="node" label="节点" />
              <el-table-column header-align="center" align="center" prop="operator" label="操作人" />
              <el-table-column header-align="center" align="center" prop="createTimes" label="操作时间" />
              <el-table-column header-align="center" align="center" prop="signer" label="签核" />
              <el-table-column header-align="center" align="center" prop="advice" label="签核意见" />
            </el-table>
          </el-card>
        </div>
      </el-tab-pane>
    </el-tabs>
  </div>
</template>

<script setup lang="ts">
import { Log, digitUppercase } from '@/utils/a_utilFunction';
import { VxeTableInstance, VxeTableEvents } from 'vxe-table'
import type { VxeTablePropTypes } from 'vxe-table'
import { VxeUI } from 'vxe-table'

interface RowVO {
  id: number;
  type: string[];
  name: string[];
  suggestedPrice: string;
  salePrice: string;
  count: string;
  totalWithoutTax: string;
  taxRate: string;
  totalWithTax: string;
  memo: string;
  finalQuotation: string;
}
const tableRef = ref<VxeTableInstance<RowVO>>()
let $table
let activeTab = ref('info')
let tabsIndexs = ['1', '2', '3', '4']
let activeNames = ref(tabsIndexs)
let row_activeNames = ref(tabsIndexs)
let hintText = ref('请输入')
const flowData = []

const sexEditRender = reactive({
  name: 'VxeSelect',
  props: {
    multiple: true
  },
  options: [
    { name: '女', code: '女' },
    { name: '男', code: '男' }
  ],
  optionProps: {
    label: 'name',
    value: 'code'
  }
})
let formInline = ref({
  projectName: '',
  quotationNo: generateRandomNumber(),
  customerName: '',
  customerAddress: '',
  contactPerson: '',
  customerTel: '',
  customerEmail: '',
  selfName: '广州瑞沃斯视觉技术有限公司',
  selfAddress: '广州市黄埔区瑞祥路188号瑞松科技园C栋4楼',
  selfContactPerson: 'admin',
  selfTel: '188888888888',
  selfEmail: 'ruiwosis@163.com',
})
//报价详情
let quotationDetail = ref({
  type: '',
  name: '',
  suggestedPrice: '',
  salePrice: '',
  count: '',
  totalWithoutTax: '',
  taxRate: '',
  totalWithTax: '',
  memo: '',
  finalQuotation: '0',
})
//备注
let memo = ref({
  deadLine: '',
  payment: {
    deadLine: '',
    prePay: '',
    afterPay: '',
    endPay: '',
  },
  delivery: '',
  qualityGuarantee: '',
  quotationValidity: ''
})
const tableData = ref<RowVO[]>([
  {
    "id": 10001,
    "type": ["男", '男'],
    "name": ['女', '女'],
    "suggestedPrice": "3000",
    "salePrice": "2900",
    "count": "1",
    "totalWithoutTax": "2900",
    "taxRate": "0",
    "totalWithTax": "2900",
    "memo": "最新型号",
    "finalQuotation": "2900"
  },
])
const roleList = ref([
  { label: '前端', value: '1', disabled: false },
  { label: '后端', value: '2', disabled: false },
  { label: '项目经理', value: '3', disabled: false },
  { label: '设计师', value: '4', disabled: false },
  { label: '运维', value: '5', disabled: false }
])

let signFlow = ref([])

const footerMethodData = ref([
  {
    type: 'add',
    index: 0
  },
  {
    type: 'column',
    index: 1,
    columns: [
      {
        text: '项目报价（未税）',
        content: [{ price: 24000 }, { price: 24000, prefix: '大写' }],
      },
      {
        text: '含税总计报价',
        content: [{ price: 55600 }, { price: 55600, prefix: '大写' }],
      },
      {
        text: '最终优惠含税总计报价',
        content: [{ price: 0 }, { price: 0, prefix: '大写' }],
        icon: { delete: false }
      },
      {
        text: '新增最终优惠含税总计报价',
        icon: { add: true },
      },
    ]
  }
])
const footerMethod: VxeTablePropTypes.FooterMethod<RowVO> = () => {
  return footerMethodData.value
}
//总是在最后一个元素前插入元素
function insertBeforeLast(arr, element) {
  if (arr.length < 2) {
    // 如果数组长度小于2，直接将元素添加到数组末尾
    arr.push(element);
  } else {
    // 插入到倒数第二个位置
    arr.splice(arr.length - 1, 0, element);
  }
  return arr;
}
//新增最终优惠含税总计报价
const addFinalTaxQuotation = (row) => {
  let targetArr = row.columns.filter(v => {
    return v.text.includes('最终优惠含税总计报价')
  })
  row.columns = insertBeforeLast(row.columns, {
    text: `新增最终优惠含税总计报价-新增${targetArr.length}`,
    content: [{ price: 0 }, { price: 0, prefix: '大写' }],
    icon: { delete: true },
  })
  footerMethodData.value[1].columns! = row.columns
  // Log(row, footerMethodData.value)
}
//找到包含class的父元素
function findParentWithClass(element, className) {
  // 确保传入的 element 是一个有效的 DOM 元素
  if (!element || !(element instanceof Element)) {
    throw new Error('Invalid DOM element');
  }

  // 向上查找直到根节点
  while (element) {
    if (element.classList && element.classList.contains(className)) {
      return element; // 返回找到的父元素
    }
    element = element.parentElement; // 继续向上查找
  }

  // 如果没有找到包含 className 的父元素，返回 null
  return null;
}
const deleteFinalTaxQuotation = (e, row) => {
  let ele = findParentWithClass(e.target, 'inline-flex');
  if (ele !== null) {
    let targetText = ele.childNodes[0].innerText;
    let index = row.columns.findIndex(v => {
      return v.text.includes(targetText)
    })
    if (index !== -1) {
      row.columns.splice(index, 1)
      Log(row)
    }
  }
}

const deleteRow = (row) => {
  VxeUI.modal.confirm({
    title: '操作提示',
    content: '请您确认是否删除？',
  }).then(v => {
    // console.log(v, row)
    if ($table) {
      $table.remove(row)
    }
  })
}

// 表尾合并
const footerColspanMethod: VxeTablePropTypes.FooterSpanMethod = ({ $rowIndex, _columnIndex }) => {
  // Log($rowIndex, _columnIndex)
  if ($rowIndex === 0) {
    if (_columnIndex === 0) {
      return {
        rowspan: 1,
        colspan: 11
      }
    } else {
      return {
        rowspan: 0,
        colspan: 0
      }
    }
  }
  if ($rowIndex === 1) {
    if (_columnIndex === 0) {
      return {
        rowspan: 1,
        colspan: 11
      }
    } else {
      return {
        rowspan: 0,
        colspan: 0
      }
    }
  }
}


const footerData = ref<VxeTablePropTypes.FooterData>([
  { seq: '合计', num: '282' },
  // { seq: '平均', num: '2.88' }
])
const formatRole = (row: RowVO) => {
  const item = roleList.value.find(item => item.value === row.role)
  return item ? item.label : row.role
}
const insertEvent = () => {
  const $table = tableRef.value
  if ($table) {
    const record = {}
    $table.insert(record)
  }
}

const updateRoleList = () => {
  const $table = tableRef.value
  if ($table) {
    // 获取表格中的全量数据
    const { fullData } = $table.getTableData()
    roleList.value.forEach(item => {
      if (item.value) {
        // 如果当前选项已经被选过，则禁用
        item.disabled = fullData.some(row => row.role === item.value)
      }
    })
  }
}

const roleChangeEvent = () => {
  updateRoleList()
}

const editActivatedEvent: VxeTableEvents.EditActivated<RowVO> = () => {
  // 激活编辑时检查剩余选项是否可选择
  updateRoleList()
}
onMounted(() => {
  updateRoleList()
  $table = tableRef.value
})
nextTick(() => {
  updateRoleList()
})

function generateRandomNumber() {
  // 获取当前日期
  const now = new Date();

  // 获取当前年份和月份
  const year = now.getFullYear();
  const month = (now.getMonth() + 1).toString().padStart(2, '0'); // 月份从0开始，因此加1，并用0填充单数字

  // 生成前六位
  const prefix = year.toString().slice(-2) + month; // 取年份的后两位，加上月份

  // 生成后六位随机数字
  const randomSuffix = Math.floor(Math.random() * 1000000).toString().padStart(6, '0'); // 保证后六位始终为6位数

  // 组合成12位数字
  return prefix + randomSuffix;
}
</script>

<style lang="scss" scoped>
.mid {
  :deep(.el-collapse-item__wrap) {
    margin-left: 60px;
  }

  :deep(.el-collapse-item__content) {
    width: 100%;
    padding: 12px 5px !important;
  }
}

:deep(.vxe-table--body-wrapper) {
  max-height: 250px !important;
  height: 202px !important;
}

:deep(.vxe-table--footer) {
  tfoot>tr:nth-child(2) {
    .footerCell {
      // height: 250px;
    }
  }
}

.card-header {
  span {
    font-weight: 700;
    font-size: 15px;
  }
}

.cards>div {
  &:nth-of-type(1) {
    margin-top: 15px;
  }

  margin-bottom: 30px;
}

.el-collapse {
  border: 1px solid rgb(211, 207, 246);

  .el-collapse-item {
    &:last-child {
      margin-bottom: 0;
    }

    :deep(.el-collapse-item__header) {
      display: none !important;
    }

    :deep(.el-collapse-item__wrap) {
      background-color: transparent;
      display: flex !important;

      .el-collapse-item__content {
        padding: 8px 5px;
      }
    }

    &:nth-child(2n + 1) {
      background-color: rgb(230, 230, 230);
    }
  }
}
</style>
